package main

import (
	"fmt"
	"net/http"
	"strings"

	"GoWebCmd/utils"

	"github.com/GeertJohan/go.rice"
)

func main() {
	http.HandleFunc("/ws", wsHandler)
	http.Handle("/", http.FileServer(rice.MustFindBox("").HTTPBox()))
	http.ListenAndServe(":7777", nil)
}

func wsHandler(resp http.ResponseWriter, req *http.Request) {
	// 应答客户端告知升级连接为websocket
	wsSocket, err := utils.WsUpgrader.Upgrade(resp, req, nil)
	if err != nil {
		return
	}

	wsConn := &utils.WsConnection{}
	wsConn.HandleRead = func(messageType int, data []byte) {
		args := strings.Split(string(data), " ")
		cmdOut := make(chan string)

		//协程处理cmd输出,并计数，用于等待完成
		go func() {
			//处理cmd输出通道的数据
			for cmdLine := range cmdOut {
				fmt.Println(cmdLine)
				wsConn.WsWrite(messageType, []byte(cmdLine))
			}
			fmt.Println("cmd接收完成")
		}()

		//协程执行cmd,并计数，用于等待完成
		go func() {
			utils.ExecCommand(args[0], args[1:], cmdOut)
			fmt.Println("cmd执行完成")
		}()
	}
	wsConn.Init(wsSocket)
	wsConn.StartLoop()
}
